<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Ajax解析模拟列表数据</title>
  <!-- 引入Tailwind CSS -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- 引入Font Awesome -->
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body class="bg-gray-50">
<div class="container mx-auto px-4 py-8 max-w-6xl">
  <header class="mb-8">
    <h1 class="text-3xl font-bold text-gray-800 mb-2">员工列表</h1>
    <p class="text-gray-600">使用Ajax获取并解析模拟的员工数据</p>
  </header>

  <div class="flex flex-wrap gap-4 mb-6">
    <button id="fetchDataBtn" class="bg-emerald-600 hover:bg-emerald-700 text-white px-6 py-3 rounded-lg transition duration-300 flex items-center shadow-md">
      <i class="fa fa-users mr-2"></i>获取员工数据
    </button>
    <button id="refreshBtn" class="bg-slate-600 hover:bg-slate-700 text-white px-6 py-3 rounded-lg transition duration-300 flex items-center shadow-md hidden">
      <i class="fa fa-refresh mr-2"></i>刷新数据
    </button>
    <button id="generateGridBtn" class="bg-emerald-600 hover:bg-emerald-700 text-white px-6 py-3 rounded-lg transition duration-300 flex items-center shadow-md">
      <i class="fa generateGridBtn mr-2"></i>生成九宫格
    </button>
  </div>

  <!-- 加载状态 -->
  <div id="loading" class="hidden py-16 text-center">
    <div class="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-emerald-500"></div>
    <p class="mt-4 text-gray-600">正在加载数据，请稍候...</p>
  </div>

  <!-- 错误提示 -->
  <div id="error" class="hidden bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg mb-6">
    <div class="flex items-start">
      <i class="fa fa-exclamation-circle mt-1 mr-3 text-red-500"></i>
      <div>
        <h3 class="font-medium" id="errorTitle">加载失败</h3>
        <p class="mt-1 text-sm" id="errorMessage">无法加载数据，请稍后重试</p>
      </div>
    </div>
  </div>

  <!-- 列表容器 -->
  <div id="employeeList" class="overflow-hidden bg-white rounded-lg shadow-md hidden">
    <table class="min-w-full divide-y divide-gray-200">
      <thead class="bg-gray-50">
      <tr>
        <th><input type="checkbox" id="selectAll"></th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">发票号</th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">类型</th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">日期</th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">金额</th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">销售方</th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">购买方</th>
        <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">预览</th>
      </tr>
      </thead>
      <tbody id="tableBody" class="bg-white divide-y divide-gray-200">
      <!-- 表格内容将通过JavaScript动态生成 -->
      </tbody>
    </table>
  </div>

  <!-- 空状态 -->
  <div id="emptyState" class="hidden bg-white rounded-lg p-12 text-center border border-gray-200">
    <i class="fa fa-user-o text-5xl text-gray-300 mb-4"></i>
    <h3 class="text-lg font-medium text-gray-900 mb-2">暂无员工数据</h3>
    <p class="text-gray-500">点击"获取员工数据"按钮加载数据</p>
  </div>
</div>

<script>
  // DOM元素引用
  const fetchDataBtn = document.getElementById('fetchDataBtn');
  const refreshBtn = document.getElementById('refreshBtn');
  const loading = document.getElementById('loading');
  const error = document.getElementById('error');
  const errorTitle = document.getElementById('errorTitle');
  const errorMessage = document.getElementById('errorMessage');
  const employeeList = document.getElementById('employeeList');
  const tableBody = document.getElementById('tableBody');
  const emptyState = document.getElementById('emptyState');

  // 绑定事件监听器
  fetchDataBtn.addEventListener('click', fetchInvoiceData);
  refreshBtn.addEventListener('click', fetchInvoiceData);

  // 模拟后端API数据生成函数
  function generateMockData() {
    // 职位和部门数据
    const positions = ['前端开发工程师', '后端开发工程师', '产品经理', 'UI设计师', '测试工程师', '数据分析师', '项目经理'];
    const departments = ['技术部', '产品部', '设计部', '测试部', '运维部', '人力资源部', '市场部'];
    const firstNames = ['张', '王', '李', '赵', '刘', '陈', '杨', '黄', '周', '吴'];
    const lastNames = ['伟', '芳', '娜', '秀英', '敏', '静', '强', '磊', '军', '洋'];

    // 生成随机日期
    function randomDate() {
      const start = new Date(2010, 0, 1);
      const end = new Date();
      const randomDate = new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
      return randomDate.toISOString().split('T')[0];
    }

    // 生成员工数据
    const employees = [];
    const count = Math.floor(Math.random() * 5) + 8; // 8-12条数据

    for (let i = 1; i <= count; i++) {
      const isActive = Math.random() > 0.1; // 90%概率在职
      const firstName = firstNames[Math.floor(Math.random() * firstNames.length)];
      const lastName = lastNames[Math.floor(Math.random() * lastNames.length)];

      employees.push({
        id: 1000 + i,
        name: firstName + lastName,
        position: positions[Math.floor(Math.random() * positions.length)],
        department: departments[Math.floor(Math.random() * departments.length)],
        hireDate: randomDate(),
        status: isActive ? '在职' : '离职'
      });
    }

    return {
      success: true,
      message: "数据加载成功",
      data: employees,
      timestamp: new Date().getTime()
    };
  }

  // 模拟404错误数据
  const mock404Data = {
    success: false,
    message: "请求的资源不存在",
    data: null,
    timestamp: new Date().getTime()
  };

  // 模拟500错误数据
  const mock500Data = {
    success: false,
    message: "服务器内部错误",
    data: null,
    timestamp: new Date().getTime()
  };

  // 获取员工数据
  function fetchEmployeeData() {
    // 显示加载状态
    showLoading();

    // 模拟Ajax请求延迟
    setTimeout(() => {
      // 随机模拟错误情况
      const random = Math.random();
      let responseData, statusCode;

      if (random < 0.15) {
        // 15%概率404错误
        responseData = mock404Data;
        statusCode = 404;
      } else if (random < 0.25) {
        // 10%概率500错误
        responseData = mock500Data;
        statusCode = 500;
      } else {
        // 75%概率返回正常数据
        responseData = generateMockData();
        statusCode = 200;
      }

      // 处理返回的数据
      handleResponse(responseData, statusCode);
    }, 1200); // 模拟1.2秒的网络延迟
  }

  // 处理响应数据
  function handleResponse(data, statusCode) {
    if (statusCode === 200 && data.success && data.data && data.data.length > 0) {
      // 成功获取数据
      renderEmployeeList(data.data);
    } else if (statusCode === 404) {
      // 404错误处理
      showError('资源未找到', '请求的接口地址不存在 (404)');
    } else if (statusCode === 500) {
      // 500错误处理
      showError('服务器错误', '服务器内部错误，请稍后重试 (500)');
    } else if (!data.success) {
      // 接口返回错误信息
      showError('加载失败', data.message || '获取数据失败');
    } else {
      // 空数据处理
      showEmptyState();
    }
  }

  // 渲染员工列表
  function fetchInvoiceData(employees) {
    // 清空表格内容
    tableBody.innerHTML = '';
    // 遍历员工数据，创建表格行
    employees.forEach(employee => {
      const row = document.createElement('tr');
      row.className = 'hover:bg-gray-50 transition-colors';

      // 根据状态设置不同颜色
      const statusClass = employee.status === '在职'
              ? 'bg-green-100 text-green-800'
              : 'bg-gray-100 text-gray-800';

      row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${employee.id}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">${employee.name}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${employee.position}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${employee.department}</td>
                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">${employee.hireDate}</td>
                    <td class="px-6 py-4 whitespace-nowrap">
                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${statusClass}">
                            ${employee.status}
                        </span>
                    </td>
                `;

      tableBody.appendChild(row);
    });

    // 显示列表，隐藏其他状态
    employeeList.classList.remove('hidden');
    refreshBtn.classList.remove('hidden');
    loading.classList.add('hidden');
    error.classList.add('hidden');
    emptyState.classList.add('hidden');
  }

  // 显示加载状态
  function showLoading() {
    loading.classList.remove('hidden');
    employeeList.classList.add('hidden');
    error.classList.add('hidden');
    emptyState.classList.add('hidden');
    refreshBtn.classList.add('hidden');
  }

  // 显示错误信息
  function showError(title, message) {
    errorTitle.textContent = title;
    errorMessage.textContent = message;
    error.classList.remove('hidden');
    loading.classList.add('hidden');
    employeeList.classList.add('hidden');
    emptyState.classList.add('hidden');
    refreshBtn.classList.remove('hidden');
  }

  // 显示空状态
  function showEmptyState() {
    emptyState.classList.remove('hidden');
    loading.classList.add('hidden');
    employeeList.classList.add('hidden');
    error.classList.add('hidden');
    refreshBtn.classList.remove('hidden');
  }
</script>
</body>
</html>
